import {createRouter, createWebHashHistory} from 'vue-router'
import {clearUserLoginStatus, getUserLoginStatus} from "@/utils/userIsLogin";
import {ElMessage} from "element-plus";

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: '/',
            name: 'home',
            component: () => import('@/views/home/index.vue'),
            meta: {
                title: '首页'
            },
            children: [
                {
                    path: 'restaurant',
                    name: 'restaurant',
                    component: () => import('@/views/admin/restaurant.vue'),
                    meta: {
                        title: '餐厅管理'
                    }
                },
                {
                    path: 'category',
                    name: 'category',
                    component: () => import('@/views/admin/category.vue'),
                    meta: {
                        title: '菜品类别'
                    }
                },
                {
                    path: 'dish',
                    name: 'dish',
                    component: () => import('@/views/admin/dish.vue'),
                    meta: {
                        title: '菜品管理'
                    }
                },
                {
                    path: 'user',
                    name: 'user',
                    component: () => import('@/views/admin/user.vue'),
                    meta: {
                        title: '用户管理'
                    }
                },
                {
                    path: 'order',
                    name: 'order',
                    component: () => import('@/views/admin/order.vue'),
                    meta: {
                        title: '订单管理'
                    }
                }
            ]
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('@/views/login/index.vue'),
            meta: {
                title: '登录'
            }
        }
    ]
})
router.beforeEach((to, from, next) => {
    const isLoggedIn = getUserLoginStatus(); // 判断用户是否已经登录
    if (to.path === '/login') {
        // 如果用户已经登录，则直接跳转到目标页面
        if (isLoggedIn) {
            next('/');
        } else {
            // 如果用户未登录，则继续访问登录页面
            next();
        }
    } else {
        // 需要登录才能访问该页面
        if (!isLoggedIn) {
            const requiresMessage = '请先登录';
            ElMessage.error(requiresMessage)
            clearUserLoginStatus();
            // 用户未登录，跳转到登录页面
            next('/login');
        } else {
            // 用户已登录，继续访问该页面
            document.title = to.meta.title
            next()
        }
    }
});

export default router
